﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;

namespace M9ContactEditor
{
	public partial class main : Form
	{
		public main()
		{
			InitializeComponent();
		}

		private void open_Click(object sender, EventArgs e)
		{
			OpenFileDialog dialog = new OpenFileDialog() { Filter = "M9联系人存档|*.xml" };
			if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
			{
				loadFile(dialog.FileName);
			}
		}

		bool isLoading = false;
		void loadFile(string file)
		{
			XmlDocument xml = new XmlDocument();
			xml.Load(file);
			if (xml.DocumentElement.Name != "ContactTable")
			{
				MessageBox.Show("打开的XML文档似乎不是M9联系人存档,请重新选择.");
				open_Click(null, null);
				return;
			}
			XmlNodeList list = xml.DocumentElement.SelectNodes("Contact");
			isLoading = true;
			foreach (XmlNode node in list)
			{
				data.Rows.Add(
					getName(node),
					getCategory(node),
					getPhones(node),
					getBody(node)
				);
			}
			isLoading = false;
			this.Text = this.Text.TrimEnd('*', ' ');
		}
		string getName(XmlNode node)
		{
			return node.SelectSingleNode("FileAs").InnerText;
		}
		string getCategory(XmlNode node)
		{
			node = node.SelectSingleNode("Category");
			return node == null ? "" : node.InnerText;
		}
		string getBody(XmlNode node)
		{
			node = node.SelectSingleNode("Body");
			return node == null ? "" : node.InnerText;
		}
		string getPhones(XmlNode node)
		{
			string phones = ""; 
			foreach (XmlNode x in node.SelectNodes("PhoneElement"))
			{
				phones += x.Attributes["Value"].Value.Trim().Replace("-", "").Replace(" ", "") + " ";
			}
			return phones.TrimEnd().Replace(" ", "/");
		}

		private void save_Click(object sender, EventArgs e)
		{
			SaveFileDialog dialog = new SaveFileDialog() { Filter = "M9联系人存档|*.xml", Title = "联系人信息保存为", FileName = "Contact.xml" };
			if (dialog.ShowDialog() != System.Windows.Forms.DialogResult.OK) return;

			XmlDocument xml = new XmlDocument();
			xml.LoadXml("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?><ContactTable><Product>M9</Product><SoftwareVersion>1.0.1</SoftwareVersion></ContactTable>");
			XmlElement root = xml.DocumentElement;

			foreach (DataGridViewRow r in data.Rows)
			{
				string name = (r.Cells[0].Value + "").Trim();
				if (name == "") continue;

				XmlNode Contact = root.AppendChild(xml.CreateElement("Contact"));

				XmlNode FileAs = Contact.AppendChild(xml.CreateElement("FileAs"));
				XmlNode FirstName = Contact.AppendChild(xml.CreateElement("FirstName"));
				XmlNode DisplayName = Contact.AppendChild(xml.CreateElement("DisplayName"));
				DisplayName.InnerText = FirstName.InnerText = FileAs.InnerText = name;

				string category = (r.Cells[1].Value + "").Trim();
				if (category != "")
				{
					XmlNode Category = Contact.AppendChild(xml.CreateElement("Category"));
					Category.InnerText = category;
				}

				string[] phones = (r.Cells[2].Value + "").Trim().Split('/');
				for (int i = 0; i < phones.Length; i++)
				{
					XmlNode PhoneElement = Contact.AppendChild(xml.CreateElement("PhoneElement"));
					PhoneElement.Attributes.Append(xml.CreateAttribute("Value")).Value = phones[i];
					PhoneElement.Attributes.Append(xml.CreateAttribute("IsPrimary")).Value = i == 0 ? "1" : "0";
					PhoneElement.Attributes.Append(xml.CreateAttribute("Type")).Value = phones[i].StartsWith("1") ? "0" : "1";
				}

				string body = (r.Cells[3].Value + "").Trim();
				if (body != "")
				{
					XmlNode Body = Contact.AppendChild(xml.CreateElement("Body"));
					Body.InnerText = body;
				}
			}

			xml.Save(dialog.FileName);

			dialog = new SaveFileDialog() { Filter = "M9联系人分组|*.xml", Title = "联系人分组信息保存为", FileName = "Group.xml" };
			if (dialog.ShowDialog() != System.Windows.Forms.DialogResult.OK) return;
			xml = new XmlDocument();
			xml.LoadXml("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?><GroupTable><Product>M9</Product><SoftwareVersion>1.0.1</SoftwareVersion></GroupTable>");
			root = xml.DocumentElement;
			
			List<string> groups = new List<string>();
			foreach (DataGridViewRow row in data.Rows)
			{
				string category = (row.Cells[1].Value + "").Trim();
				if (category == "" || groups.Contains(category)) continue;

				groups.Add(category);
				XmlNode GroupInfo = root.AppendChild(xml.CreateElement("GroupInfo"));
				XmlNode GroupItem = GroupInfo.AppendChild(xml.CreateElement("GroupItem"));
				GroupItem.Attributes.Append(xml.CreateAttribute("GroupName")).Value = category;
			}

			xml.Save(dialog.FileName);

			this.Text = this.Text.TrimEnd('*', ' ');
		}

		private void data_CellEndEdit(object sender, DataGridViewCellEventArgs e)
		{
			this.Text = this.Text.TrimEnd('*', ' ') + " *";
		}

		private void del_Click(object sender, EventArgs e)
		{
			if (data.SelectedRows.Count > 1 && MessageBox.Show("选中了多行.确定删除?", "提示", MessageBoxButtons.OKCancel) == DialogResult.Cancel) return;
			
			foreach (DataGridViewRow row in data.SelectedRows)
			{
				if (!row.IsNewRow) data.Rows.Remove(row);
			}
		}

		private void data_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
		{
			if (e.RowIndex > 1 && !isLoading)
				data.Rows[e.RowIndex - 1].Cells[1].Value = data.Rows[e.RowIndex - 2].Cells[1].Value;
		}

		private void help_Click(object sender, EventArgs e)
		{
			StringBuilder sb = new StringBuilder();
			sb.AppendLine("1. 打开的文件必须是联系人存档,编辑存档之前要先进行备份,使用备份档中的Contact.xml进行编辑.");
			sb.AppendLine("2. 保存联系人后会生成一个联系人文档,和一个分组信息文档.还原联系人时必须把这两个文件一起拷到原位置.");
			sb.AppendLine("3. 同一个人有多个号码时,号码之间用\"/\"分隔,第一个号码将成为联系人的首选号码.");
			sb.AppendLine("4. 手动添加新联系人时,默认添加到上一行联系人的分组.");
			MessageBox.Show(sb.ToString());
		}
	}
}
